package com.softserveinc.cheatsheet.entity;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
@NamedQueries({
		@NamedQuery(name = UserAccount.GET_USER_ACCOUNT_BY_NAME_QUERY, query = "from UserAccount where username = :name"),
		@NamedQuery(name = UserAccount.LIST_USER_ACCOUNT_BY_NAME_QUERY, query = "from UserAccount order by username") })
public class UserAccount implements Serializable, UserDetails {
	public static final String GET_USER_ACCOUNT_BY_NAME_QUERY = "getUserAccountByName";

	public static final String LIST_USER_ACCOUNT_BY_NAME_QUERY = "listUserAccountByName";
	private static final long serialVersionUID = 1L;

	@ManyToMany(targetEntity = UserAuthority.class)
	@JoinTable(name = "USR_AUTH", joinColumns = @JoinColumn(name = "USR_ID"), inverseJoinColumns = @JoinColumn(name = "AUTH_ID"))
	private Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	private String username;
	private String password;

	public UserAccount() {
	}

	public UserAccount(String username) {
		super();
		this.username = username;
	}

	
	public void addAuthority(UserAuthority someAuthority) {
		authorities.add(someAuthority);
	}

	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		return this.authorities;
	}

	public Long getId() {
		return id;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Column(unique = true, nullable = false)
	public String getUsername() {
		return username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	public void setAuthorities(Set<GrantedAuthority> authorities) {
		this.authorities = authorities;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public String toString() {
		return "UserAccount [authorities=" + authorities + ", id=" + id
				+ ", password=" + password + ", username=" + username + "]";
	}

}
